package com.base.asynctaks;

import android.os.AsyncTask;
import android.widget.TextView;

import com.base.util.MLog;
import com.base.util.StringUtil;

import java.util.concurrent.TimeUnit;

/**
 * Created by yjh on 15-3-11.
 */
public class CountDownTask extends AsyncTask<Integer, Integer, Integer> {
    //用于显示倒计时的TextView
    private TextView textView;
    //倒计时前后的文本信息
    private String msgStart;
    private String msgEnd;
    private StringBuilder sb = new StringBuilder();
    //倒计时结束后设置的文本
    private String msgResult;

    public CountDownTask(TextView textView,
                         String msgStart, String msgEnd, String msgResult) {
        this.msgResult = msgResult;
        this.textView = textView;
        this.msgStart = msgStart;
        this.msgEnd = msgEnd;
    }

    @Override
    protected Integer doInBackground(Integer... integers) {
        int startCount = integers[0];
        while(startCount >= 0) {
            try {
                this.publishProgress(startCount--);
                TimeUnit.SECONDS.sleep(1); //任务开始有一定延时，故将停顿放在之后
            } catch (Exception e) {
                MLog.e(e);
            }

        }

        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        textView.setEnabled(false);
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        sb.setLength(0);
        textView.setText(sb.append(StringUtil.emptyIfBlank(msgStart)).append(values[0]).append(StringUtil.emptyIfBlank(msgEnd)));
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
        textView.setText(StringUtil.emptyIfBlank(msgResult));
        textView.setEnabled(true);
    }
}
